package com.sykj.seaflow.warm.core.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.dromara.warm.flow.core.entity.HisTask;
import org.dromara.warm.flow.core.entity.Task;
import org.dromara.warm.flow.orm.entity.FlowHisTask;
import org.dromara.warm.flow.orm.entity.FlowTask;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.poi.excel.sax.AttributeName.r;

public class FlowStatusUtil {

    public static String flowStatus(String flowJson,
                                    List<HisTask> hisTaskList, List<Task> taskList){
        if(hisTaskList == null){
            hisTaskList = new ArrayList<>();
        }
        if(taskList == null){
            taskList = new ArrayList<>();
        }

        JSONObject nodeData = JSONUtil.parseObj(flowJson);
        findNodeStatus(nodeData, hisTaskList, taskList);
        return JSONUtil.toJsonStr(nodeData);
    };
    private static void  findNodeStatus(JSONObject nodeData,List<HisTask> hisTaskList, List<Task> taskList){
        JSONArray nodeStatus = new JSONArray();
        nodeData.set("nodeStatus", nodeStatus);
        List<HisTask> hisTasks = hisTaskList.stream().filter(r -> ObjectUtil.equal(r.getNodeCode(), nodeData.getStr("nodeId"))).collect(Collectors.toList());
        List<Task> tasks = taskList.stream().filter(r -> ObjectUtil.equal(r.getNodeCode(), nodeData.getStr("nodeId"))).collect(Collectors.toList());
        if(ObjectUtil.isNotEmpty(hisTasks)){
            for(HisTask hisTask: hisTasks){
                nodeStatus.put(hisTask.getFlowStatus());

            }
        }
        if(ObjectUtil.isNotEmpty(tasks)){
            nodeStatus.put("1");  //表示待审批
        }
        JSONObject childNode = nodeData.getJSONObject("childNode");
        if(childNode != null){
            findNodeStatus(childNode, hisTaskList,taskList);
        }
        JSONArray conditionNodes = nodeData.getJSONArray("conditionNodes");
        if(conditionNodes != null){
            for(Object node: conditionNodes){
                findNodeStatus((JSONObject)node,hisTaskList,taskList);
            }
        }
    }
}



